package com.brest.tools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;
import android.os.AsyncTask;

import com.brest.managesambafilesharing.LOG;

public class RunAsRoot {
	public static final String TAG = "managesambafilesharing";
	private Context context = null;
	private String[] commands = {
			"ls -l /data/data/com.funkyfresh.samba/files/samba-rc*",
			"ls -l /data/data/com.brest.samba/Scripts/samba-rc*" };

	OnResponseListenerRunAsRoot responder;

	public interface OnResponseListenerRunAsRoot {
		public void onResponse(String message);
	}

	// Asynchronously posts to twitter
	private class RunAsRootAsyncTask extends AsyncTask<String, Integer, String> { //

		@Override
		protected String doInBackground(String... statuses) { //
			String res = "!";

			try {

				RunAsRoot.runAsRoot(commands);

				res = "done";
			} catch (Exception e) {
				LOG.e(e.toString());
				e.printStackTrace();
				res = "Failed to doInBackground";
			}
			return res;
		}

		protected void onPreExecute() {
			LOG.i("Pre-Execute");
			super.onPreExecute();
		}

		// Called when there's a status to be updated
		@Override
		protected void onProgressUpdate(Integer... values) { //
			super.onProgressUpdate(values);
			// Not used in this case
		}

		// Called once the background activity has completed
		@Override
		protected void onPostExecute(String result) {
			LOG.i("onPostExecute");
			if (responder != null) {
				responder.onResponse(result);
			}
		}
	}

	private String[] getCommands() {
		return commands;
	}

	private void setCommands(String[] commands) {
		this.commands = commands;
	}

	private static StringBuilder runAsRoot(String[] cmds) {
		Process p;
		StringBuilder res = new StringBuilder();

		try {
			p = Runtime.getRuntime().exec("su -");
			DataOutputStream os = new DataOutputStream(p.getOutputStream());
			BufferedReader in = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			for (String tmpCmd : cmds) {
				os.writeBytes(tmpCmd + "\n");
			}
			os.writeBytes("exit\n");
			os.flush();
			String line = null;
			while ((line = in.readLine()) != null) {
				// Log.i(TAG, line);
				res.append(line + "\n");
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}

	public void start(String pcommands[],
			OnResponseListenerRunAsRoot onResponseListener) {
		responder = onResponseListener;
		if (pcommands != null) {
			commands = pcommands;
			LOG.i("start()");
			new RunAsRootAsyncTask().execute("status");
		} else {
			if (pcommands == null) {
				LOG.i("pcommands == null");
			}
		}
	}
}
